#!/usr/bin/env bash
set -e -u -o pipefail

declare -r SCRIPT_DIR=$(cd -P $(dirname $0) && pwd)

declare -r NAMESPACE=${NAMESPACE:-hello-openshift}

declare -r VERSION=${VERSION:-$(date +%s)}

declare -r NAME=${NAME:-nginx-proxy}

declare -r PIPELINE_NAME=${PIPELINE_NAME:-build-and-deploy}

declare -r GIT_URL=${GIT_URL:-https://gitee.com/xwofwang/nginx-openshift.git}

_log() {
    local level=$1; shift
    echo -e "$level: $@"
}

log.err() {
    _log "ERROR" "$@" >&2
}

info() {
    _log "\nINFO" "$@"
}

err() {
    local code=$1; shift
    local msg="$@"; shift
    log.err $msg
    exit $code
}

valid_command() {
  local fn=$1; shift
  [[ $(type -t "$fn") == "function" ]]
}

# helpers to avoid adding -n $NAMESPACE to oc and tkn
OC() {
  echo oc -n "$NAMESPACE" "$@"
  oc -n "$NAMESPACE" "$@"
}

TKN() {
 echo tkn -n "$NAMESPACE" "$@"
 tkn -n "$NAMESPACE" "$@"
}

demo.validate_tools() {
  info "validating tools"

  tkn version >/dev/null 2>&1 || err 1 "no tkn binary found"
  oc version  >/dev/null 2>&1 || err 1 "no oc binary found"
  return 0
}


bootstrap() {
    demo.validate_tools

    info "ensure namespace $NAMESPACE exists"
    OC get ns "$NAMESPACE" 2>/dev/null  || {
      OC new-project $NAMESPACE
    }
  }


demo.logs() {
  TKN pipeline logs $PIPELINE_NAME --last -f
}

demo.run() {
  info "Running gradle & maven Build and deploy"

  TKN pipeline start $PIPELINE_NAME \
      -w name=shared-workspace,volumeClaimTemplateFile=03_persistent_volume_claim.yaml \
      -p deployment-name=$NAME \
      -p git-url=$GIT_URL \
      -p IMAGE=image-registry.openshift-image-registry.svc:5000/$NAMESPACE/$NAME:$VERSION \
      --use-param-defaults


  info "Validating the result of pipeline run"
  demo.validate_pipelinerun
}

demo.run_local() {
  info "build docker"
  podman build -t $NAME:$VERSION .

  info "oc login"
  OC login -u=developer

  info "login default openshift internal registry"
  echo podman login -u kubeadmin -p $(oc whoami -t) default-route-openshift-image-registry.apps-crc.testing --tls-verify=false

  podman login -u kubeadmin -p $(oc whoami -t) default-route-openshift-image-registry.apps-crc.testing --tls-verify=false

  info "tag local image"
  echo podman tag localhost/$NAME:$VERSION default-route-openshift-image-registry.apps-crc.testing/$NAMESPACE/$NAME:$VERSION

  podman tag localhost/$NAME:$VERSION default-route-openshift-image-registry.apps-crc.testing/$NAMESPACE/$NAME:$VERSION

  info "push to internal registry"
  echo podman push default-route-openshift-image-registry.apps-crc.testing/$NAMESPACE/$NAME:$VERSION

  podman push default-route-openshift-image-registry.apps-crc.testing/$NAMESPACE/$NAME:$VERSION


  info "replace image"
  sed "s/NNAMESPACEN/${NAMESPACE}/g" k8s/deployment.yaml.temp > k8s/deployment.temp.1
  sed "s/NNAMEN/${NAME}/g" k8s/deployment.temp.1 > k8s/deployment.temp.2
  sed "s/NVERSIONN/${VERSION}/g" k8s/deployment.temp.2 > k8s/deployment.yaml

  info "Running  Build and deploy"
  OC apply -f k8s/.

  rm k8s/deployment.yaml
  rm k8s/deployment.temp.*

}

demo.validate_pipelinerun() {
  local failed=0
  local results=( $(oc get pipelinerun.tekton.dev -n "$NAMESPACE" --template='
    {{range .items -}}
      {{ $pr := .metadata.name -}}
      {{ $c := index .status.conditions 0 -}}
      {{ $pr }}={{ $c.type }}{{ $c.status }}
    {{ end }}
    ') )

  for result in ${results[@]}; do
    if [[ ! "${result,,}" == *"=succeededtrue" ]]; then
      echo "ERROR: test $result but should be SucceededTrue"
      failed=1
    fi
  done

  return "$failed"
}


demo.help() {
# NOTE: must insert leading TABS and not SPACE to align
  cat <<-EOF
		USAGE:
		  demo [command]

		COMMANDS:
		  run               starts pipeline to deploy api, ui
		  logs              shows logs of last pipelinerun
EOF
}

main() {
  local fn="demo.${1:-help}"
  valid_command "$fn" || {
    demo.help
    err  1 "invalid command '$1'"
  }

  cd "$SCRIPT_DIR"
  $fn "$@"
  return $?
}

main "$@"
